﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TowerDefender.Model;

namespace TowerDefender.Model
{
    public class Peon
    {
        private Coordinates _coordinates;
        private Coordinates _oldCoordinates;
        private int positionInMapPath = 0;
        // the time it takes for this object to move, the greater, the slower
        private int _pace;
        private int _paceCounter;
        private Map _map;
        private Engine _engine;
        public int direction;
        public event EventHandler CoordinatesChanged;
        private int _delayToStart;
        private bool _started;
        private bool _visible;

        public Peon(Map map, Engine engine, int pace, int delayToStart)
        {
            _pace = pace;
            _map = map;
            _engine = engine;
            _engine.Tick += new EventHandler(engine_Tick);
            _coordinates = _map.MapPath.Points[0];
            _oldCoordinates = _coordinates;
            _delayToStart = delayToStart;
            _started = false;
            _visible = false;
        }

        public bool Visible { get { return _visible; } }
        public int Pace { get { return _pace; } }


        public Coordinates Coordinates 
        {
            get
            {
                return _coordinates;
            }
            set 
            { 
                _coordinates = value;
                if (CoordinatesChanged != null)
                {
                    CoordinatesChanged(this, new EventArgs());
                }
            }
        }

        public Coordinates OldCoordinates
        {
            get
            {
                return _oldCoordinates;
            }
        }

        void engine_Tick(object sender, EventArgs e)
        {
            if (!_started && _paceCounter < _delayToStart)
            {
                _paceCounter++;
                return;
            }
            else
            {
                _visible = true;
                _started = true;
            }

            if (_paceCounter++ < _pace)
            {
                return;
            }
            else
            {
                _paceCounter = 0;
            }

            if (positionInMapPath < _map.MapPath.Points.Count)
            {
                this._oldCoordinates = this._coordinates;
                this.Coordinates = _map.MapPath.Points[positionInMapPath++];
            }
            else
            {
                this.Coordinates = null;
                this._visible = false;
            }
        }
    }
}
